package com.mall.order.mq.order;

import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.order.dto.OrderDetailRequest;
import com.mall.order.dto.OrderDetailResponse2;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Description:
 * @Author: JK
 * @Date: create in 2021/7/23 17:48
 */
@Slf4j
@Component
public class DelayOrderConsumer {
    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    OrderQueryService orderQueryService;

    private DefaultMQPushConsumer consumer;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("delay_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("delay_order_cancel", "*");
            consumer.setMessageListener(new MessageListenerConcurrently() {
                @SneakyThrows
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    // 1.取出消息中的orderId
                    MessageExt message = msgs.get(0);
                    byte[] body = message.getBody();
                    String orderId = new String(body, 0, body.length, "utf-8");

                    // 2.根据orderId查询订单，如果订单仍未支付，则取消订单；如果订单已经成功支付，什么都不做
                    OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
                    orderDetailRequest.setOrderId(orderId);
                    OrderDetailResponse2 orderDetail = orderQueryService.queryOrderDetail(orderDetailRequest);

                    if (orderDetail.getOrderStatus().equals(OrderConstants.ORDER_STATUS_INIT)) {
                        // 如果订单仍未支付，则取消订单
                        // 取消订单的逻辑：a.修改订单状态为已取消7，b.恢复锁定的商品库存
                        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
                        cancelOrderRequest.setOrderId(orderId);
                        CancelOrderResponse cancelOrderResponse = orderCoreService.cancelOrder(cancelOrderRequest);
                        if (OrderRetCode.SUCCESS.getCode().equals(cancelOrderResponse.getCode())) {
                            log.info("DelayOrderConsumer Consumer成功接收到订单延迟消息，" + orderId + "：订单超时已经自动取消！");
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    // 如果订单已经成功支付，什么都不做
                    log.info("DelayOrderConsumer Consumer成功接收到订单延迟消息，" + orderId + "：订单已经支付！");
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            // 启动消费者
            consumer.start();
        } catch (MQClientException e) {
            log.info("DelayOrderConsumer#init Occur Exception: " + e);
            e.printStackTrace();
        }
    }
}
